const db = wx.cloud.database();
import util from "../../utils/util.js"
// pages/PayNow/PayNow.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
	address: {},
	checkedCar: [],
	goods_id: '',
	totalPrice: 0,
	total: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	const eventChannel = this.getOpenerEventChannel()
	eventChannel.on('sendGoodsId', (data) => {
		this.setData({
			goods_id: data.goods_id
		})
		this.getGoodsDetail();
	})
  
  
  },
  
  onShow(){
	  const address = wx.getStorageSync("address");
	  this.setData({
		  address
	  })
  },
  
  async getGoodsDetail() {
  	const goodsObject = await db.collection('goods_index')
  		.where({
  			"message.goods_id": Number(this.data.goods_id)
  		})
  		.get()
  		.then(res => {
  			let {checkedCar} = this.data
  			checkedCar.push(res.data[0].message);
  			checkedCar[0].num = 1;
  			console.log(checkedCar)
  			this.setData({
  				checkedCar,
  				total: checkedCar[0].num,
  				totalPrice: checkedCar[0].goods_price
  				
  			})
  		})
  },
  
  PayOfBuy() {
  	const token = wx.getStorageSync("token");
  	const userInfo = wx.getStorageSync("userInfo");
  	if (!token) {
  		wx.navigateTo({
  			url: "/pages/author/author"
  		})
  		return;
  	} else if (!userInfo) {
  		wx.navigateTo({
  			url: "/pages/login/login"
  		})
		return;
  	} else {
  		const nowDate = util.formatTime(new Date());
  		db.collection('order_List').add({
  				data: {
  					orderName: this.data.address.userName,
  					orderPhone: this.data.address.telNumber,
  					orderAdress: this.data.address.allAddress,
  					orderTime: nowDate,
  					goods: this.data.checkedCar,
  					totalPrice: this.data.totalPrice,
  					type: 1
  				}
  			})
  			.then((res) => {
  				wx.showToast({
  					title: "下单完成！",
  					icon: "success",
  					mask: true
  				})
  				//页面出栈
  				wx.redirectTo({
  					url: "/pages/order/order?type=1"
  				});
  			})
  
  	}
  }
})